<?php


namespace app\api\controller\Goods;


use app\api\controller\AppController;
use app\api\model\Collage\CollageModel;
use app\api\model\Goods\GoodsAttrModel;
use app\api\model\Goods\GoodsAttrValueModel;
use app\api\model\Goods\GoodsModel;
use app\api\model\Order\OrderGoodsModel;
use app\api\model\Order\OrderModel;
use app\api\model\System\SysSettingModel;
use app\api\model\User\UserAddressModel;
use app\api\model\User\UserCouponModel;
use app\api\model\User\UserWalletModel;
use app\Request;
use app\Utils\CalculateUtil;
use app\Utils\ImageUtil;
use app\Utils\StrUtil;
use app\Utils\Util;
use app\Utils\WechatPayUtil;
use Exception;
use think\facade\Db;

class GoodsOrder extends AppController
{

    /**
     * @api {post} /per_order_info 获取预创建订单信息
     * @apiGroup 商品
     * @apiParam {string} token Token
     * @apiParam {array} list 商品集合[{goods_id:"商品ID",'number':"数量",'unique':"属性unique"}]
     * @apiParam {int} is_group 是否拼团 0： 是 1：否
     * @apiParam {int} collage_id 拼团ID
     * @apiParam {int} user_coupon_id 优惠券ID
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function preOrderInfo(Request $request)
    {
        $param = $request->param();
        //用户优惠券ID
        $user_coupon_id = !empty($param['user_coupon_id']) ? $param['user_coupon_id'] : 0;
        $user = $this->user;
        if (empty($user)) {
            return Util::returnJson(self::CODE_LOGIN, null, "请登录");
        }

        if (empty($param['list']) && empty($param['list'])) {
            return Util::returnJson(self::CODE_ERROR, null, "参数错误5");
        } else {
            $goods_str = urldecode($param['list']);
            $goods_str = json_decode($goods_str);
            $data_list = [];
            foreach ($goods_str as $item) {
                $var = json_decode($item, true);
                array_push($data_list, $var);
            }
            unset($item);
            $param['list'] = $data_list;
        }

        //当前商品用户的优惠券列表
        $user_coupon_list = [];
        foreach ($param['list'] as $val) {
            $cou_where = [
                ['uid', '=', $user['id']],
                ['label', '=', 2],
                ['type', '=', 2],
                ['goods_ids', 'like', '%' . $val['goods_id'] . ',' . '%'],
                ['start_time', '<', date("Y-m-d H:i:s", time())],
                ['end_time', '>', date("Y-m-d H:i:s", time())],
                ['status', '=', 0]
            ];
            $cou_where_1 = [
                ['uid', '=', $user['id']],
                ['type', '=', 1],
                ['label', '=', 2],
                ['start_time', '<', date("Y-m-d H:i:s", time())],
                ['end_time', '>', date("Y-m-d H:i:s", time())],
                ['status', '=', 0]
            ];
            $coupon_list = UserCouponModel::getUserCouponWhereOrMore([$cou_where, $cou_where_1]);
            foreach ($coupon_list as $item) {
                $coupon_data = json_decode($item['coupon_data'], true);
                $array['id'] = $item['id'];
                $array['uid'] = $item['uid'];
                $array['coupon_id'] = $item['coupon_id'];
                $array['coupon_title'] = $coupon_data['coupon_title'];
                $array['status'] = $item['status'];
                $array['goods_ids'] = $item['goods_ids'];
                $array['amount'] = $item['amount'];
                $array['total_amount'] = $item['total_amount'];
                $array['start_time'] = $item['start_time'];
                $array['end_time'] = $item['end_time'];
                array_push($user_coupon_list, $array);
            }
            unset($item);
        }

        //总价格
        $total_all_price = 0;
        //总数量
        $number = 0;
        //总抵扣
        $all_deduction_price = 0;
        //总邮费
        $all_postage = 0;

        //商品列表
        $list = [];

//        if (!empty($goodsInfo['is_group'])) {
//            //检测商品
////            if (count($param['list']) > 1) {
////                return Util::returnJson(self::CODE_ERROR, null, "拼团商品只能拼一个");
////            }
//        }
        //优惠券 true全场券还是false指定商品券
        $coupon_flag = false;
        if (!empty($user_coupon_id)) {
            //有使用优惠券
            $user_coupon = UserCouponModel::getUserCouponWhere([['id', '=', $user_coupon_id]]);
            if (!empty($user_coupon)) {
                if ($user_coupon['label'] != 2) {
                    return Util::returnJson(self::CODE_ERROR, null, "优惠券类型错误");
                }
            } else {
                return Util::returnJson(self::CODE_ERROR, null, "优惠券错误");
            }
        }

        foreach ($param['list'] as $item) {
            if (empty($item['goods_id']) && empty($item['goods_id'])) {
                return Util::returnJson(self::CODE_ERROR, null, "参数错误6");
            }
            if (empty($item['number']) && empty($item['number'])) {
                return Util::returnJson(self::CODE_ERROR, null, "请选择商品数量");
            }
            $goodsInfo = GoodsModel::getGoodsWhere(['id' => $item['goods_id'], 'is_show' => 1, 'is_del' => 0]);

            if (!empty($goodsInfo['is_discounts'])) {
                if ($item['number'] > 1) {
                    return Util::returnJson(self::CODE_ERROR, null, "特惠商品只能买一个");
                }
            }

            if (!empty($goodsInfo['is_group'])) {
                //验证拼团是否已满
                if (!empty($param['collage_id'])) {
                    $collage = CollageModel::getCollageWhere([['id', '=', $param['collage_id']]]);
                    if (!empty($collage)) {
                        if (strtotime($collage['end_time']) > time()) {
                            if ($collage['status'] != 0 || $collage['collage_count'] <= $collage['now_count']) {
                                return Util::returnJson(self::CODE_ERROR, null, "拼团已满");
                            }
                        } else {
                            return Util::returnJson(self::CODE_ERROR, null, "拼团时间已过期");
                        }
                    } else {
                        return Util::returnJson(self::CODE_ERROR, null, "拼团不存在");
                    }
                }
//                if ($item['number'] > 1) {
//                    return Util::returnJson(self::CODE_ERROR, null, "拼团商品只能买一个");
//                }
            }

            if (empty($goodsInfo)) {
                return Util::returnJson(self::CODE_ERROR, null, "商品不存在或已下架");
            } else {
                if (!empty($item['unique'])) {
                    $attr_value = GoodsAttrValueModel::getGoodsAttrValueWhere(['unique' => $item['unique']]);
                    if (!$attr_value) {
                        return Util::returnJson(self::CODE_ERROR, null, "商品" . $goodsInfo['good_name'] . "规格不存在或已下架");
                    }
                    if ($attr_value['stock'] < $item['number']) {
                        return Util::returnJson(self::CODE_ERROR, null, "商品" . $goodsInfo['good_name'] . "规格库存不足，无法购买");
                    }
                    $attr_value['group_price'] = $goodsInfo['group_price'];
                    $attr_value['group_num'] = $goodsInfo['group_num'];
                } else {
                    $attr = GoodsAttrModel::getGoodsAttrWhereMore([['goods_id', '=', $item['goods_id']]]);
                    if (!empty($attr)) {
                        return Util::returnJson(self::CODE_ERROR, null, "请选择商品" . $goodsInfo['good_name'] . "的规格");
                    }
                    if ($goodsInfo['stock'] < $item['number']) {
                        return Util::returnJson(self::CODE_ERROR, null, "商品" . $goodsInfo['good_name'] . "库存不足，无法购买");
                    }
                    $attr_value = [
                        'price' => $goodsInfo['price'],
                        'vip_price' => $goodsInfo['vip_price'],
                        'group_price' => $goodsInfo['group_price'],
                        'group_num' => $goodsInfo['group_num'],
                        'suk' => $goodsInfo['good_name']
                    ];
                }
            }

            $price = 0;
            //价格
            if (!empty($param['is_group'])) {
                //拼团
                $price = $attr_value['group_price'];
            } else {
                if (!empty($user['level_id']) && (!empty($user['is_level_type']) || strtotime($user['end_time']) > time())) {
                    //VIP
                    $price = $attr_value['vip_price'];
                } else {
                    $price = $attr_value['price'];
                }
            }

            $total_price = $price * $item['number'];

            //抵扣
            //邮费
            $postage = 0;
            //每个商品抵扣
            $deduction_price = 0;
            if (empty($param['is_group'])) {
                if (!empty($user_coupon)) {
                    if (strtotime($user_coupon['start_time']) < time() && strtotime($user_coupon['end_time']) > time()) {
                        if (empty($user_coupon['status'])) {
                            if ($user_coupon['type'] == 2) {
                                $goods_ids = explode(',', trim($user_coupon['goods_ids'], ','));
                                if (in_array($item['goods_id'], $goods_ids)) {
                                    if ($user_coupon['attr'] == 1) {
                                        //立减
                                        $deduction_price += $user_coupon['amount'];
                                        $total_price = bcsub($total_price, $user_coupon['amount'], 2);
                                    }
                                    if ($user_coupon['attr'] == 2) {
                                        //满减
                                        if ($total_price > $user_coupon['total_amount']) {
                                            $deduction_price += $user_coupon['amount'];
                                            $total_price = bcsub($total_price, $user_coupon['amount'], 2);
                                        }
                                    }
                                    if ($user_coupon['attr'] == 3) {
                                        //立减折扣(打折)
                                        $amount = bcmul($total_price, bcdiv($user_coupon['amount'], 100), 2);
                                        $deduction_price += bcsub($total_price, $amount, 2);
                                        $total_price = $amount;
                                    }
                                    if ($user_coupon['attr'] == 4) {
                                        //满减折扣(打折)
                                        if ($total_price > $user_coupon['total_amount']) {
                                            $amount = bcmul($total_price, bcdiv($user_coupon['amount'], 100), 2);
                                            $deduction_price += bcsub($total_price, $amount, 2);
                                            $total_price = $amount;
                                        }
                                    }
                                }
                            } else {
                                $coupon_flag = true;
                            }
                        } else {
                            return Util::returnJson(self::CODE_ERROR, null, "优惠券已使用或已过期");
                        }
                    } else {
                        return Util::returnJson(self::CODE_ERROR, null, "优惠券已过期");
                    }
                }
            } else {
                if (!empty($user_coupon)) {
                    return Util::returnJson(self::CODE_ERROR, null, "拼团无法使用优惠券");
                }
            }
            //总抵扣
            $all_deduction_price += $deduction_price;
            //总邮费
            if (empty($goodsInfo['is_postage'])) {
                $postage = $goodsInfo['postage'];
            }
            $all_postage += $postage;

            $number += $item['number'];
            $total_all_price += $total_price;
            $goodsInfo['img'] = json_decode($goodsInfo['img'], true);
            $goods_remarks = [
                "type" => 1,
                "goods_id" => $goodsInfo['id'],
                "unique" => !empty($item['unique']) ? $item['unique'] : "",
                "total_price" => $total_price,
                'is_postage' => $goodsInfo['is_postage'],
                'postage' => $postage,
                "deduction_price" => !empty($deduction_price) ? $deduction_price : 0,
                "number" => $item['number'],
                "goods_price" => $price,
                "suk" => $attr_value['suk'],
                "goods_info" => $goodsInfo,
                "user_coupon_id" => empty($coupon_flag) ? $user_coupon_id : 0,//优惠券ID
            ];
            array_push($list, $goods_remarks);
        }

        //全场优惠券
        if ($coupon_flag && !empty($user_coupon)) {
            if ($user_coupon['attr'] == 1) {
                //立减
                $all_deduction_price += $user_coupon['amount'];
                $total_all_price = bcsub($total_all_price, $user_coupon['amount'], 2);
            }
            if ($user_coupon['attr'] == 2) {
                //满减
                if ($total_all_price > $user_coupon['total_amount']) {
                    $all_deduction_price += $user_coupon['amount'];
                    $total_all_price = bcsub($total_all_price, $user_coupon['amount'], 2);
                }
            }
            if ($user_coupon['attr'] == 3) {
                //立减折扣(打折)
                $amount = bcmul($total_all_price, bcdiv($user_coupon['amount'], 100), 2);
                $all_deduction_price += bcsub($total_all_price, $amount, 2);
                $total_all_price = $amount;
            }
            if ($user_coupon['attr'] == 4) {
                //满减折扣(打折)
                if ($total_all_price > $user_coupon['total_amount']) {
                    $amount = bcmul($total_all_price, bcdiv($user_coupon['amount'], 100), 2);
                    $all_deduction_price += bcsub($total_all_price, $amount, 2);
                    $total_all_price = $amount;
                }
            }
        }


        //获取默认地址
        $data = [
            'token' => $param['token'],
            'is_group' => !empty($param['is_group']) ? $param['is_group'] : 0,
            'collage_id' => !empty($param['collage_id']) ? $param['collage_id'] : 0,
            'list' => $list,
            'count' => count($list),
            'number' => $number,
            'total_price' => bcadd($total_all_price, $all_postage, 2),
            'postage' => $all_postage,
            'deduction_price' => !empty($all_deduction_price) ? $all_deduction_price : 0,
            'user_coupon_id' => $user_coupon_id,//优惠券ID
            'user_coupon_list' => $user_coupon_list //当前商品用户的优惠券
        ];
        $address = UserAddressModel::getUserAddressWhere(['uid' => $user['id'], 'is_default' => 1]);
        if (!empty($address)) {
            $data['address'] = $address;
        } else {
            $data['address'] = [];
        }
        return Util::returnJson(self::CODE_SUCCESS, $data, "");
    }

    /**
     * @api {post} /create_goods_order 商品订单提交支付
     * @apiGroup 商品
     * @apiParam {string} token Token
     * @apiParam {int} source_type 来源 1:APP 2:微信公众号 3:小程序
     * @apiParam {int} pay_way 支付方式 1：余额  2:支付宝 3：微信
     * @apiParam {int} address_id 收货地址ID
     * @apiParam {array} list 商品集合[{goods_id:"商品ID",'number':"数量",'unique':"属性unique"}]
     * @apiParam {int} is_group 是否拼团 0： 是 1：否
     * @apiParam {int} collage_id 拼团ID
     * @apiParam {int} user_coupon_id 优惠券ID
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function createGoodsOrder(Request $request)
    {
        $param = $request->param();
        //用户优惠券ID
        $user_coupon_id = !empty($param['user_coupon_id']) ? $param['user_coupon_id'] : 0;
        $user = $this->user;
        if (empty($user)) {
            return Util::returnJson(self::CODE_LOGIN, null, "请登录");
        }
        //1:APP 2:微信公众号 3:小程序
        if (!in_array($param['source_type'], [1, 2, 3])) {
            return Util::returnJson(self::CODE_ERROR, null, "来源错误");
        }
        if (!in_array($param['pay_way'], [1, 2, 3])) {
            return Util::returnJson(self::CODE_ERROR, null, "支付类型错误");
        }

        $address = UserAddressModel::getUserAddressWhere(['id' => $param['address_id']]);
        if (empty($address)) {
            return Util::returnJson(self::CODE_ERROR, null, "请选择收获地址");
        }

        if (empty($param['list']) && empty($param['list'])) {
            return Util::returnJson(self::CODE_ERROR, null, "参数错误5");
        } else {
            $goods_str = urldecode($param['list']);
            $goods_str = json_decode($goods_str);
            $data_list = [];
            foreach ($goods_str as $item) {
                $var = json_decode($item, true);
                array_push($data_list, $var);
            }
            unset($item);
            $param['list'] = $data_list;
        }

        //优惠券 true全场券还是false指定商品券
        $coupon_flag = false;
        if (!empty($user_coupon_id)) {
            //有使用优惠券
            $user_coupon = UserCouponModel::getUserCouponWhere([['id', '=', $user_coupon_id]]);
            if (!empty($user_coupon)) {
                if ($user_coupon['label'] != 2) {
                    return Util::returnJson(self::CODE_ERROR, null, "优惠券类型错误");
                }
            } else {
                return Util::returnJson(self::CODE_ERROR, null, "优惠券错误");
            }
        }


        //总价格
        $total_all_price = 0;
        //总数量
        $number = 0;
        //总抵扣
        $all_deduction_price = 0;
        //总邮费
        $all_postage = 0;

        //商品列表
        $list = [];

//        if (!empty($goodsInfo['is_group'])) {
//            //检测商品
//            if (count($param['list']) > 1) {
//                return Util::returnJson(self::CODE_ERROR, null, "拼团商品只能拼一个");
//            }
//        }

        foreach ($param['list'] as $item) {
            if (empty($item['goods_id']) && empty($item['goods_id'])) {
                return Util::returnJson(self::CODE_ERROR, null, "参数错误6");
            }
            if (empty($item['number']) && empty($item['number'])) {
                return Util::returnJson(self::CODE_ERROR, null, "请选择商品数量");
            }
            $goodsInfo = GoodsModel::getGoodsWhere(['id' => $item['goods_id'], 'is_show' => 1, 'is_del' => 0]);

            if (!empty($goodsInfo['is_discounts'])) {
                if ($item['number'] > 1) {
                    return Util::returnJson(self::CODE_ERROR, null, "特惠商品只能买一个");
                }
            }

            if (!empty($goodsInfo['is_group'])) {
//                //检测商品
//                if (count($param['list']) > 1) {
//                    return Util::returnJson(self::CODE_ERROR, null, "拼团商品只能拼一个");
//                }
                //验证拼团是否已满
                if (!empty($param['collage_id'])) {
                    $collage = CollageModel::getCollageWhere([['id', '=', $param['collage_id']]]);
                    if (!empty($collage)) {
                        if ($collage['uid'] == $user['id']) {
                            return Util::returnJson(self::CODE_ERROR, null, "不能加入自己的团");
                        }
                        if (strtotime($collage['end_time']) > time()) {
                            if ($collage['status'] != 0 || $collage['collage_count'] <= $collage['now_count']) {
                                return Util::returnJson(self::CODE_ERROR, null, "拼团已满");
                            }
                        } else {
                            return Util::returnJson(self::CODE_ERROR, null, "拼团时间已过期");
                        }
                    } else {
                        return Util::returnJson(self::CODE_ERROR, null, "拼团不存在");
                    }
                }
                if ($item['number'] > 1) {
                    return Util::returnJson(self::CODE_ERROR, null, "拼团商品只能买一个");
                }
            }

            if (empty($goodsInfo)) {
                return Util::returnJson(self::CODE_ERROR, null, "商品不存在或已下架");
            } else {
                if (!empty($item['unique'])) {
                    $attr_value = GoodsAttrValueModel::getGoodsAttrValueWhere(['unique' => $item['unique']]);
                    if (!$attr_value) {
                        return Util::returnJson(self::CODE_ERROR, null, "商品" . $goodsInfo['good_name'] . "规格不存在或已下架");
                    }
                    if ($attr_value['stock'] < $item['number']) {
                        return Util::returnJson(self::CODE_ERROR, null, "商品" . $goodsInfo['good_name'] . "规格库存不足，无法购买");
                    }
                    $attr_value['group_price'] = $goodsInfo['group_price'];
                    $attr_value['group_num'] = $goodsInfo['group_num'];
                } else {
                    $attr = GoodsAttrModel::getGoodsAttrWhereMore([['goods_id', '=', $item['goods_id']]]);
                    if (!empty($attr)) {
                        return Util::returnJson(self::CODE_ERROR, null, "请选择商品" . $goodsInfo['good_name'] . "的规格");
                    }
                    if ($goodsInfo['stock'] < $item['number']) {
                        return Util::returnJson(self::CODE_ERROR, null, "商品" . $goodsInfo['good_name'] . "库存不足，无法购买");
                    }
                    $attr_value = [
                        'price' => $goodsInfo['price'],
                        'vip_price' => $goodsInfo['vip_price'],
                        'group_price' => $goodsInfo['group_price'],
                        'group_num' => $goodsInfo['group_num'],
                        'suk' => $goodsInfo['good_name']
                    ];
                }
            }

            $price = 0;
            if (!empty($param['is_group'])) {
                $price = $attr_value['group_price'];
            } else {
                //价格
                if (!empty($user['level_id']) && (!empty($user['is_level_type']) || strtotime($user['end_time']) > time())) {
                    //VIP
                    $price = $attr_value['vip_price'];
                } else {
                    $price = $attr_value['price'];
                }
            }

            $total_price = $price * $item['number'];

            //抵扣
            //邮费
            $postage = 0;
            //每个商品抵扣
            $deduction_price = 0;
            if (empty($param['is_group'])) {
                if (!empty($user_coupon)) {
                    if (strtotime($user_coupon['start_time']) < time() && strtotime($user_coupon['end_time']) > time()) {
                        if (empty($user_coupon['status'])) {
                            if ($user_coupon['type'] == 2) {
                                $goods_ids = explode(',', trim($user_coupon['goods_ids'], ','));
                                if (in_array($item['goods_id'], $goods_ids)) {
                                    if ($user_coupon['attr'] == 1) {
                                        //立减
                                        $deduction_price += $user_coupon['amount'];
                                        $total_price = bcsub($total_price, $user_coupon['amount'], 2);
                                    }
                                    if ($user_coupon['attr'] == 2) {
                                        //满减
                                        if ($total_price > $user_coupon['total_amount']) {
                                            $deduction_price += $user_coupon['amount'];
                                            $total_price = bcsub($total_price, $user_coupon['amount'], 2);
                                        }
                                    }
                                    if ($user_coupon['attr'] == 3) {
                                        //立减折扣(打折)
                                        $amount = bcmul($total_price, bcdiv($user_coupon['amount'], 100), 2);
                                        $deduction_price += bcsub($total_price, $amount, 2);
                                        $total_price = $amount;
                                    }
                                    if ($user_coupon['attr'] == 4) {
                                        //满减折扣(打折)
                                        if ($total_price > $user_coupon['total_amount']) {
                                            $amount = bcmul($total_price, bcdiv($user_coupon['amount'], 100), 2);
                                            $deduction_price += bcsub($total_price, $amount, 2);
                                            $total_price = $amount;
                                        }
                                    }
                                }
                            } else {
                                $coupon_flag = true;
                            }
                        } else {
                            return Util::returnJson(self::CODE_ERROR, null, "优惠券已使用或已过期");
                        }
                    } else {
                        return Util::returnJson(self::CODE_ERROR, null, "优惠券已过期");
                    }
                }
            }
            //总抵扣
            $all_deduction_price += $deduction_price;
            //总邮费
            if (empty($goodsInfo['is_postage'])) {
                $postage = $goodsInfo['postage'];
            }
            $all_postage += $postage;

            $number += $item['number'];
            $total_all_price += $total_price;
            $goods_remarks = [
                "type" => 1,
                "goods_id" => $goodsInfo['id'],
                "unique" => !empty($item['unique']) ? $item['unique'] : "",
                "total_price" => $total_price,
                'is_postage' => $goodsInfo['is_postage'],
                'postage' => $postage,
                "deduction_price" => !empty($deduction_price) ? $deduction_price : 0,
                "number" => $item['number'],
                "goods_price" => $price,
                "suk" => $attr_value['suk'],
                "goods_info" => $goodsInfo,
                "mer_id" => $goodsInfo['mer_id'],
                "ratio" => $goodsInfo['merchant_ratio'],
            ];
            /*if(!empty($param['is_group'])){
                $goods_remarks['group_price'] = $attr_value['group_price'];
                $goods_remarks['group_num']   = $attr_value['group_num'];
            }*/
            array_push($list, $goods_remarks);
        }
        Db::startTrans();
        try {
            if (!empty($param['is_group'])) {
                if (!empty($param['collage_id'])) {
                    //加入团
                    $collage = CollageModel::getCollageWhere([['id', '=', $param['collage_id']]]);
                    if ($collage['collage_count'] > $collage['now_count']) {
                        $collage_id = $param['collage_id'];
                    }
                }
            }

            //全场优惠券
            if ($coupon_flag && !empty($user_coupon)) {
                if ($user_coupon['attr'] == 1) {
                    //立减
                    $all_deduction_price += $user_coupon['amount'];
                    $total_all_price = bcsub($total_all_price, $user_coupon['amount'], 2);
                }
                if ($user_coupon['attr'] == 2) {
                    //满减
                    if ($total_all_price > $user_coupon['total_amount']) {
                        $all_deduction_price += $user_coupon['amount'];
                        $total_all_price = bcsub($total_all_price, $user_coupon['amount'], 2);
                    }
                }
                if ($user_coupon['attr'] == 3) {
                    //立减折扣(打折)
                    $amount = bcmul($total_all_price, bcdiv($user_coupon['amount'], 100), 2);
                    $all_deduction_price += bcsub($total_all_price, $amount, 2);
                    $total_all_price = $amount;
                }
                if ($user_coupon['attr'] == 4) {
                    //满减折扣(打折)
                    if ($total_all_price > $user_coupon['total_amount']) {
                        $amount = bcmul($total_all_price, bcdiv($user_coupon['amount'], 100), 2);
                        $all_deduction_price += bcsub($total_all_price, $amount, 2);
                        $total_all_price = $amount;
                    }
                }
            }

            //商户订单号
            $out_trade_no = StrUtil::i()->getOrderSn(3);
            //商品订单号
            $order_sn = StrUtil::i()->getOrderSn();
            $data = [
                'order_sn' => $order_sn,
                'uid' => $user['id'],
                'type' => 1,
                'total_price' => bcadd($total_all_price, $all_postage, 2),
                'postage' => $all_postage,
                "deduction_price" => !empty($all_deduction_price) ? $all_deduction_price : 0,
                'username' => $address['username'],
                'mobile' => $address['mobile'],
                'address' => $address['region'] . $address['detailed'],
                'up_time' => date('Y-m-d H:i:s', time()),
                'add_time' => date('Y-m-d H:i:s', time()),
                'pay_way' => $param['pay_way'],
                'source_type' => $param['source_type'],
                'pay_num' => $number,
                'is_discounts' => !empty($param['is_discounts']) ? 1 : 0,
                'is_group' => !empty($param['is_group']) ? $param['is_group'] : 0,
                'collage_id' => 0,
                'temp_collage_id' => !empty($collage_id) ? $collage_id : 0,
                'user_coupon_id' => !empty($user_coupon_id) ? $user_coupon_id : 0,
                'mer_id' => $goodsInfo ? $goodsInfo['mer_id'] : 0 //小店ID

            ];

            //价格小于0 默认0
            if ($data['total_price'] < 0) {
                $data['total_price'] = 0;
            }

            $order_id = OrderModel::addOrder($data);
            if (!empty($order_id)) {
                //修改优惠券状态
                if (!empty($user_coupon_id)) {
                    $coupon_save = [
                        'status' => 1,
                        'up_time' => date("Y-m-d H:i:s", time())
                    ];
                    UserCouponModel::updateUserCouponWhere([['id', '=', $user_coupon_id]], $coupon_save);
                }

                foreach ($list as &$order_goods) {
                    $order_goods['goods_info'] = json_encode($order_goods['goods_info']);
                    $order_goods['order_id'] = $order_id;
                    $order_goods['is_sales'] = $goodsInfo['is_sales'];
                    $order_goods['up_time'] = date("Y-m-d H:i:s", time());
                    $order_goods['add_time'] = date("Y-m-d H:i:s", time());

                    //--------开始分销计算--------
                    $order_goods_data = CalculateUtil::i()->commissionCalculate($user, $goodsInfo, $total_all_price, $order_goods);
                    //添加订单商品
                    $flag = OrderGoodsModel::addOrderGoods($order_goods_data);
                    if (!$flag) {
                        Db::rollback();
                        return Util::returnJson(self::CODE_ERROR, null, "订单创建失败");
                    }
                    //--------结束分销计算--------
                }
                $result1 = null;
                $result = null;
                //支付
                if ($param['pay_way'] == 1) {
                    //余额支付
                } else if ($param['pay_way'] == 2) {
                    $order_save = [
                        'out_trade_no' => $out_trade_no
                    ];
                    OrderModel::updateOrderWhere([['id', '=', $order_id]], $order_save);
                    //支付宝支付
                    $result = $this->aliPay($data['total_price'], $out_trade_no, "商品支付");
                } else if ($param['pay_way'] == 3) {
                    //微信支付
                    $order_save = [
                        'out_trade_no' => $out_trade_no
                    ];
                    OrderModel::updateOrderWhere([['id', '=', $order_id]], $order_save);
                    $wx = new WechatPayUtil();
                    $result1 = $wx->wechat_pay($out_trade_no, $data['total_price'], '商品支付');
                }

                if ($result['code'] == 0) {
                    //提交保存
                    $data = [
                        'pay_way' => $param['pay_way'],
                        'pay_info' => $result ? $result['data'] : '',
                        'wx_pay' => $result1
                    ];
                    Db::commit();
                    return Util::returnJson(self::CODE_SUCCESS, $data, "下单成功");
                } else {
                    Db::rollback();
                    return Util::returnJson(self::CODE_ERROR, null, $result['msg']);
                }
            } else {
                Db::rollback();
                return Util::returnJson(self::CODE_ERROR, null, "订单创建失败");
            }
        } catch (Exception $e) {
            Db::rollback();
            var_dump($e);
            return Util::returnJson(self::CODE_ERROR, null, "下单失败！");
        }
    }

}